﻿using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model.Db.Hr.Bill;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Wtm.Models;

namespace HengTong.ViewModel.Hr.SysHrJobAssignmentRequestBillVms;

public partial class SysHrJobAssignmentRequestBillBatchVm
{
    //批量删除
    public async Task<bool> DoBatchDeleteAsync()
    {
        if (Ids == null || !Ids.Any())
        {
            MSD.AddModelError(" ", "请选择要删除的岗位分配申请单");
            return false;
        }

        // 统一转换ID，避免重复定义
        var mainIds = Ids.Select(Guid.Parse).ToList();

        // 检查单据状态和流程状态，只有单据状态为草稿且流程状态为待提交的才能删除
        var hasInvalidStatus = await DC.Set<SysHrJobAssignmentRequestBill>()
            .Where(p => mainIds.Contains(p.ID))
            .AsNoTracking()
            .AnyAsync(p => p.BillStatus != BillStatus.草稿 ||
                           !p.WorkflowStatus.HasValue ||
                           p.WorkflowStatus != WorkflowStatus.待提交);

        /*if (hasInvalidStatus)
        {
            MSD.AddModelError(" ", "只有单据状态为草稿且流程状态为待提交的记录才能删除");
            return false;
        }*/

        var transaction = await DC.Database.BeginTransactionAsync();
        try
        {
            // 删除子表数据
            var nullableIds = mainIds.Select(x => (Guid?)x).ToList();
            await DC.Set<SysHrJobAssignmentRequestBillEntry>()
                .Where(d => nullableIds.Contains(d.JobAssignmentId))
                .ExecuteDeleteAsync<SysHrJobAssignmentRequestBillEntry>();

            // 删除主表数据
            await DC.Set<SysHrJobAssignmentRequestBill>().Where(p => mainIds.Contains(p.ID)).ExecuteDeleteAsync();
            await DC.SaveChangesAsync();

            await transaction.CommitAsync();
            return true;
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            var errorMessage = e.Message;
            if (e.InnerException != null)
            {
                errorMessage += " " + e.InnerException.Message;
            }

            if (errorMessage.Contains("DELETE 语句与") ||
                errorMessage.Contains("REFERENCE 约束") ||
                errorMessage.Contains("FK_") ||
                errorMessage.Contains("constraint") ||
                errorMessage.Contains("外键约束"))
            {
                MSD.AddModelError(" ", "删除失败，该记录存在关联数据，请先删除相关信息");
            }
            else
            {
                MSD.AddModelError(" ", "删除失败，请联系管理员");
            }

            return false;
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }
}